#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>
#include <iostream>
#include <netinet/tcp.h>

// 在 initializeNetwork() 方法中替换硬编码的端口
void MainWindow::initializeNetwork()
{
    //for ICS ............................................................................................................................
    // 使用配置的TCP端口
    serverPort = ConfigManager::instance().icstcpPort();
    tcpServer = new QTcpServer(this);

    if (!tcpServer->listen(QHostAddress::Any, serverPort)) {
        LOG_GENERAL("TCP Server failed to start: " + tcpServer->errorString());
    } else {
        connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection);
        LOG_GENERAL(QString("TCP Server started on port %1").arg(serverPort));
    }

    // for MCU...............................................................................................................................
    //使用配置的UDP端口
    TempHeartSocket = new QUdpSocket(this);
    //if (!TempHeartSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
    if (!TempHeartSocket->bind(QHostAddress::Any, 12000)) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + TempHeartSocket->errorString());
    } else {
        connect(TempHeartSocket, &QUdpSocket::readyRead, this, &MainWindow::processTempHeartData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }

    VacuumHeartSocket = new QUdpSocket(this);
    //if (!VacuumHeartSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
    if (!VacuumHeartSocket->bind(QHostAddress::Any, 12100)) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + VacuumHeartSocket->errorString());
    } else {
        connect(VacuumHeartSocket, &QUdpSocket::readyRead, this, &MainWindow::processVacuumHeartData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }

    IOHeartSocket = new QUdpSocket(this);
    //if (!IOHeartSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
    if (!IOHeartSocket->bind(QHostAddress::Any, 12200)) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + IOHeartSocket->errorString());
    } else {
        connect(IOHeartSocket, &QUdpSocket::readyRead, this, &MainWindow::processIOHeartData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }

    CoolerHeartSocket = new QUdpSocket(this);
    //if (!IOHeartSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
    if (!CoolerHeartSocket->bind(QHostAddress::Any, 12300)) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + CoolerHeartSocket->errorString());
    } else {
        connect(CoolerHeartSocket, &QUdpSocket::readyRead, this, &MainWindow::processCoolerData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }


    McuActionSocket = new QUdpSocket(this);
    //if (!McuActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
    if (!McuActionSocket->bind(QHostAddress::Any, 12001)) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + McuActionSocket->errorString());
    } else {
        connect(McuActionSocket, &QUdpSocket::readyRead, this, &MainWindow::processMCUActionData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }

    //FOR camera  主ps   .....................................................................................................................
    CameraHeatSocket = new QUdpSocket(this);
    //if (!CameraHeatSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!CameraHeatSocket->bind(QHostAddress::Any, 11000)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + CameraHeatSocket->errorString());
    } else {
        connect(CameraHeatSocket, &QUdpSocket::readyRead, this, &MainWindow::processCameraHeartResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    CameraActionSocket = new QUdpSocket(this);
    //if (!CameraActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!CameraActionSocket->bind(QHostAddress::Any, 11001)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + CameraActionSocket->errorString());
    } else {
        connect(CameraActionSocket, &QUdpSocket::readyRead, this, &MainWindow::processCameraActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    //FOR camera  从ps   .............................................................................................................................
    SlaveHeatSocket1 = new QUdpSocket(this);
    //if (!SlaveHeatSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveHeatSocket1->bind(QHostAddress::Any, 13000)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveHeatSocket1->errorString());
    } else {
        connect(SlaveHeatSocket1, &QUdpSocket::readyRead, this, &MainWindow::processSlaveHeatResponse1);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveHeatSocket2 = new QUdpSocket(this);
    //if (!SlaveHeatSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveHeatSocket2->bind(QHostAddress::Any, 13100)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveHeatSocket2->errorString());
    } else {
        connect(SlaveHeatSocket2, &QUdpSocket::readyRead, this, &MainWindow::processSlaveHeatResponse2);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveHeatSocket3 = new QUdpSocket(this);
    //if (!SlaveHeatSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveHeatSocket3->bind(QHostAddress::Any, 13200)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveHeatSocket3->errorString());
    } else {
        connect(SlaveHeatSocket3, &QUdpSocket::readyRead, this, &MainWindow::processSlaveHeatResponse3);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveHeatSocket4 = new QUdpSocket(this);
    //if (!SlaveHeatSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveHeatSocket4->bind(QHostAddress::Any, 13300)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveHeatSocket4->errorString());
    } else {
        connect(SlaveHeatSocket4, &QUdpSocket::readyRead, this, &MainWindow::processSlaveHeatResponse4);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    //for 4720................................................................
    CameraActionSocket4720 = new QUdpSocket(this);
    //if (!CameraActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!CameraActionSocket4720->bind(QHostAddress::Any, 11002)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + CameraActionSocket4720->errorString());
    } else {
        connect(CameraActionSocket4720, &QUdpSocket::readyRead, this, &MainWindow::processCameraActionResponse4720);
        LOG_GENERAL(QString("Camera UDP Socket bound to port 11002"));
    }

    serverPort4720 = 9086;
    tcpServer4720 = new QTcpServer(this);

    if (!tcpServer4720->listen(QHostAddress::Any, serverPort4720)) {
        LOG_GENERAL("TCP Server failed to start: " + tcpServer4720->errorString());
    } else {
        connect(tcpServer4720, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection4720);
        LOG_GENERAL(QString("TCP Server started on port %1").arg(serverPort4720));
    }



/*
    SlaveActionSocket1 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveActionSocket1->bind(QHostAddress::Any, 13001)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveActionSocket1->errorString());
    } else {
        connect(SlaveActionSocket1, &QUdpSocket::readyRead, this, &MainWindow::processSlaveActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveActionSocket2 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveActionSocket2->bind(QHostAddress::Any, 13101)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveActionSocket2->errorString());
    } else {
        connect(SlaveActionSocket2, &QUdpSocket::readyRead, this, &MainWindow::processSlaveActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveActionSocket3 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveActionSocket3->bind(QHostAddress::Any, 13201)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveActionSocket3->errorString());
    } else {
        connect(SlaveActionSocket3, &QUdpSocket::readyRead, this, &MainWindow::processSlaveActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    SlaveActionSocket4 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveActionSocket4->bind(QHostAddress::Any, 13301)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveActionSocket4->errorString());
    } else {
        connect(SlaveActionSocket4, &QUdpSocket::readyRead, this, &MainWindow::processSlaveActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }*/

    SlaveActionServer1 = new QTcpServer(this);

    if (!SlaveActionServer1->listen(QHostAddress::Any, 13001)) {
        LOG_GENERAL("TCP Server failed to start: " + SlaveActionServer1->errorString());
    } else {
        connect(SlaveActionServer1, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection1);
        LOG_GENERAL(QString("TCP Server started on port %1").arg("13001"));
    }

    SlaveActionServer2 = new QTcpServer(this);

    if (!SlaveActionServer2->listen(QHostAddress::Any, 13101)) {
        LOG_GENERAL("TCP Server failed to start: " + SlaveActionServer2->errorString());
    } else {
        connect(SlaveActionServer2, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection2);
        LOG_GENERAL(QString("TCP Server started on port %1").arg("13101"));
    }

    SlaveActionServer3 = new QTcpServer(this);

    if (!SlaveActionServer3->listen(QHostAddress::Any, 13201)) {
        LOG_GENERAL("TCP Server failed to start: " + SlaveActionServer3->errorString());
    } else {
        connect(SlaveActionServer3, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection3);
        LOG_GENERAL(QString("TCP Server started on port %1").arg("13201"));
    }

    SlaveActionServer4 = new QTcpServer(this);

    if (!SlaveActionServer4->listen(QHostAddress::Any, 13301)) {
        LOG_GENERAL("TCP Server failed to start: " + SlaveActionServer4->errorString());
    } else {
        connect(SlaveActionServer4, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection4);
        LOG_GENERAL(QString("TCP Server started on port %1").arg("13301"));
    }


    SlaveRateActionSocket1 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveRateActionSocket1->bind(QHostAddress::Any, 13002)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveRateActionSocket1->errorString());
    } else {
        connect(SlaveRateActionSocket1, &QUdpSocket::readyRead, this, &MainWindow::processSlaveRateActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port 13002"));
    }

    SlaveRateActionSocket2 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveRateActionSocket2->bind(QHostAddress::Any, 13102)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveRateActionSocket2->errorString());
    } else {
        connect(SlaveRateActionSocket2, &QUdpSocket::readyRead, this, &MainWindow::processSlaveRateActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port 13102"));
    }

    SlaveRateActionSocket3 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveRateActionSocket3->bind(QHostAddress::Any, 13202)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveRateActionSocket3->errorString());
    } else {
        connect(SlaveRateActionSocket3, &QUdpSocket::readyRead, this, &MainWindow::processSlaveRateActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port 13202"));
    }

    SlaveRateActionSocket4 = new QUdpSocket(this);
    //if (!SlaveActionSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
    if (!SlaveRateActionSocket4->bind(QHostAddress::Any, 13302)) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + SlaveRateActionSocket4->errorString());
    } else {
        connect(SlaveRateActionSocket4, &QUdpSocket::readyRead, this, &MainWindow::processSlaveRateActionResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port 13302"));
    }


    // 更新从板卡IP配置
    for (int i = 0; i < 4; ++i) {
        statusLeds.slave[i].ip = ConfigManager::instance().slaveIp(i);
    }

    // 获取本地IP（排除回环地址）
    foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && !address.isLoopback()) {
            m_localIp = address.toString();
            break;
        }
    }
}

void MainWindow::handleNewConnection()
{
    // 输出到终端（确保编码正确）
    // QTextStream out(stdout);
    // out.setCodec("UTF-8");  // 设置控制台输出编码
    while (tcpServer->hasPendingConnections()) {
        QTcpSocket *client = tcpServer->nextPendingConnection();

//        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);   // added by XYH@20250808 01:46:40
//        // 对于 Linux/Unix 系统，可进一步调整参数
//        #ifdef Q_OS_UNIX
//        out << "**> setting tcp_keepalive ...**\n";
//        int fd = client->socketDescriptor();
//        if (fd != -1) {
//            int idle = 60;     // 60秒后开始发送keepalive探测
//            int interval = 10; // 每10秒发送一次探测
//            int count = 5;     // 尝试5次
//            
//            setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
//            setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));
//            setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &count, sizeof(count));
//        }
//        #endif

        // 启用系统级别的TCP KeepAlive
        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

        // 在支持的系统上可以进一步设置参数
        #ifdef Q_OS_LINUX
                int fd = client->socketDescriptor();
                int keepalive = 1;
                int keepidle = 60; // 60秒无活动后开始探测
                int keepinterval = 5; // 探测间隔5秒
                int keepcount = 3; // 最多探测3次
                setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
                setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
                setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
        #endif

        // 设置连接超时（例如30秒）
//         QTimer::singleShot(1000000, client, [client]() {
//           if (client->state() == QAbstractSocket::ConnectedState) {
//                 client->disconnectFromHost();
//            }
//         });

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            parseProtocol(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);

//        qDebug() << "New connection from:"
//                 << client->peerAddress().toString()
//                 << ":" << client->peerPort();
//        LOG_CAMERA("New connection from:" + client->peerAddress().toString() + ":" << client->peerPort());
        
        // 输出到终端（确保编码正确）
        // QTextStream out(stdout);
        // out.setCodec("UTF-8");  // 设置控制台输出编码
        // out << "New connection from:"
        //          << client->peerAddress().toString()
        //          << ":" << client->peerPort() << "\n";
        
    }
}
void MainWindow::sendResponseslave1(const QString &response, QTcpSocket *client)
{
    LOG_CAMERA(response);
    if (!client) {
        qDebug() << "[Error] Client socket is null";
        return;
    } else {
        // qDebug() << "Sending response before:" << response;

        if (client->state() != QAbstractSocket::ConnectedState) {
            // qDebug() << "[Warning] Client not connected, skipping response";
            return;
        } else {
            // qDebug() << "Sending response after:" << response;
            client->write(response.toUtf8());
        }
    }
}
void MainWindow::processslaveactiondata1(const QString &command, QTcpSocket *client)
{
    //LOG_CAMERA("Received slave response: " + command);
    // 分类处理响应
    if (command.startsWith("get_frame_290:done=")) {
        LOG_CAMERA("Received Slave response: " + command);
        //sendResponseslave1("get_frame_done_ok", client);
        client->disconnectFromHost(); // 立即断开连接
        handleFrameDone(command);
    }
}
void MainWindow::handleNewConnection1()
{
    while (SlaveActionServer1->hasPendingConnections()) {
        QTcpSocket *client = SlaveActionServer1->nextPendingConnection();

        // 启用系统级别的TCP KeepAlive
        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

// 在支持的系统上可以进一步设置参数
    #ifdef Q_OS_LINUX
            int fd = client->socketDescriptor();
            int keepalive = 1;
            int keepidle = 60; // 60秒无活动后开始探测
            int keepinterval = 5; // 探测间隔5秒
            int keepcount = 3; // 最多探测3次
            setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
            setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
            setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
    #endif

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            processslaveactiondata1(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);
    }
}

void MainWindow::sendResponseslave2(const QString &response, QTcpSocket *client)
{
    LOG_CAMERA(response);
    if (!client) {
        qDebug() << "[Error] Client socket is null";
        return;
    } else {
        // qDebug() << "Sending response before:" << response;

        if (client->state() != QAbstractSocket::ConnectedState) {
            // qDebug() << "[Warning] Client not connected, skipping response";
            return;
        } else {
            // qDebug() << "Sending response after:" << response;
            client->write(response.toUtf8());
        }
    }
}
void MainWindow::processslaveactiondata2(const QString &command, QTcpSocket *client)
{
   // LOG_CAMERA("Received slave response: " + command);
    // 分类处理响应
    if (command.startsWith("get_frame_290:done=")) {
        LOG_CAMERA("Received Slave response: " + command);
        //sendResponseslave2("get_frame_done_ok", client);
        client->disconnectFromHost(); // 立即断开连接
        handleFrameDone(command);
    }
}
void MainWindow::handleNewConnection2()
{
    while (SlaveActionServer2->hasPendingConnections()) {
        QTcpSocket *client = SlaveActionServer2->nextPendingConnection();

        // 启用系统级别的TCP KeepAlive
        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

        // 在支持的系统上可以进一步设置参数
#ifdef Q_OS_LINUX
        int fd = client->socketDescriptor();
        int keepalive = 1;
        int keepidle = 60; // 60秒无活动后开始探测
        int keepinterval = 5; // 探测间隔5秒
        int keepcount = 3; // 最多探测3次
        setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
        setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
        setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
#endif

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            processslaveactiondata2(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);
    }
}

void MainWindow::sendResponseslave3(const QString &response, QTcpSocket *client)
{
    LOG_CAMERA(response);
    if (!client) {
        qDebug() << "[Error] Client socket is null";
        return;
    } else {
        // qDebug() << "Sending response before:" << response;

        if (client->state() != QAbstractSocket::ConnectedState) {
            // qDebug() << "[Warning] Client not connected, skipping response";
            return;
        } else {
            // qDebug() << "Sending response after:" << response;
            client->write(response.toUtf8());
        }
    }
}
void MainWindow::processslaveactiondata3(const QString &command, QTcpSocket *client)
{
   // LOG_CAMERA("Received slave response: " + command);
    // 分类处理响应
    if (command.startsWith("get_frame_290:done=")) {
        LOG_CAMERA("Received Slave response: " + command);
        //sendResponseslave3("get_frame_done_ok", client);
        client->disconnectFromHost(); // 立即断开连接
        handleFrameDone(command);
    }
}
void MainWindow::handleNewConnection3()
{
    while (SlaveActionServer3->hasPendingConnections()) {
        QTcpSocket *client = SlaveActionServer3->nextPendingConnection();

        // 启用系统级别的TCP KeepAlive
        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

        // 在支持的系统上可以进一步设置参数
#ifdef Q_OS_LINUX
        int fd = client->socketDescriptor();
        int keepalive = 1;
        int keepidle = 60; // 60秒无活动后开始探测
        int keepinterval = 5; // 探测间隔5秒
        int keepcount = 3; // 最多探测3次
        setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
        setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
        setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
#endif

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            processslaveactiondata3(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);
    }
}

void MainWindow::sendResponseslave4(const QString &response, QTcpSocket *client)
{
    LOG_CAMERA(response);
    if (!client) {
        qDebug() << "[Error] Client socket is null";
        return;
    } else {
        // qDebug() << "Sending response before:" << response;

        if (client->state() != QAbstractSocket::ConnectedState) {
            // qDebug() << "[Warning] Client not connected, skipping response";
            return;
        } else {
            // qDebug() << "Sending response after:" << response;
            client->write(response.toUtf8());
        }
    }
}
void MainWindow::processslaveactiondata4(const QString &command, QTcpSocket *client)
{
    //LOG_CAMERA("Received slave response: " + command);
    // 分类处理响应
    if (command.startsWith("get_frame_290:done=")) {
        LOG_CAMERA("Received Slave response: " + command);
        //sendResponseslave4("get_frame_done_ok", client);
        client->disconnectFromHost(); // 立即断开连接
        handleFrameDone(command);
    }
}
void MainWindow::handleNewConnection4()
{
    while (SlaveActionServer4->hasPendingConnections()) {
        QTcpSocket *client = SlaveActionServer4->nextPendingConnection();

        // 启用系统级别的TCP KeepAlive
        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

        // 在支持的系统上可以进一步设置参数
#ifdef Q_OS_LINUX
        int fd = client->socketDescriptor();
        int keepalive = 1;
        int keepidle = 60; // 60秒无活动后开始探测
        int keepinterval = 5; // 探测间隔5秒
        int keepcount = 3; // 最多探测3次
        setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
        setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
        setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
#endif

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            processslaveactiondata4(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);
    }
}
// Link按钮点击处理
void MainWindow::onLinkToCameraClicked() {
    //生成精确到毫秒的时间戳 (格式: YYMMDDhhmmsszzz)
    QString timestamp = QDateTime::currentDateTime().toString("yyMMddhhmmsszzz");

    QString cmd1 = QString("link_to_camera:$ip=192.168.0.233$port=11000$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);
    QString cmd2 = QString("link_to_camera:$ip=192.168.0.233$port=11000$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);

    sendActionCommandToMCU(cmd1);
    LOG_CAMERA("Device registration information has been sent: " + cmd1);
    sendCameraActionCommand(cmd2);
    //querySlaveStatus();
    QString cmd3 = QString("link_to_camera:$ip=192.168.0.233$port=13000$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);
    QString cmd4 = QString("link_to_camera:$ip=192.168.0.233$port=13100$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);
    QString cmd5 = QString("link_to_camera:$ip=192.168.0.233$port=13200$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);
    QString cmd6 = QString("link_to_camera:$ip=192.168.0.233$port=13300$systime=%1$mnt=%2").arg(timestamp).arg(mountPath);
    /*sendCommandToSlave1(cmd3, "192.168.0.101");
    sendCommandToSlave2(cmd4, "192.168.0.102");
    sendCommandToSlave3(cmd5, "192.168.0.103");
    sendCommandToSlave4(cmd6, "192.168.0.104");*/
    sendCommandToSlave(cmd3, statusLeds.slave[0].ip);
    sendCommandToSlave(cmd4, statusLeds.slave[1].ip);
    sendCommandToSlave(cmd5, statusLeds.slave[2].ip);
    sendCommandToSlave(cmd6, statusLeds.slave[3].ip);
}

//配置保存修改
/*void MainWindow::on_btnSetCameraIp_clicked()
{
    QString newIp = ui->lineEditCameraIp->text();
    ConfigManager::instance().setValue("Network", "CameraIP", newIp);
    cameraIp = newIp;
}*/


void MainWindow::readClientData()
{
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (!client) return;

    while (client->bytesAvailable()) {
        QString command = QString::fromUtf8(client->readAll());
        LOG_GENERAL("Received command: " + command);
        parseProtocol(command, client);
    }
}

void MainWindow::clientDisconnected()
{
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (client) {
        qDebug() << "Client disconnected:"
                 << client->peerAddress().toString()
                 << ":" << client->peerPort();
        client->deleteLater();
        
        // 输出到终端（确保编码正确）
        // QTextStream out(stdout);
        // out.setCodec("UTF-8");  // 设置控制台输出编码
        // out << ">> Connection from:"
        //          << client->peerAddress().toString()
        //          << ":" << client->peerPort() << " [Closed]\n";
    }
}

void MainWindow::handleNewConnection4720()
{
    while (tcpServer4720->hasPendingConnections()) {
        QTcpSocket *client = tcpServer4720->nextPendingConnection();

        client->setSocketOption(QAbstractSocket::KeepAliveOption, 1);

#ifdef Q_OS_LINUX
        int fd = client->socketDescriptor();
        int keepalive = 1;
        int keepidle = 60; // 60秒无活动后开始探测
        int keepinterval = 5; // 探测间隔5秒
        int keepcount = 3; // 最多探测3次
        setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
        setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &keepinterval, sizeof(keepinterval));
        setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &keepcount, sizeof(keepcount));
#endif

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            parseProtocol4720(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);
    }
}
